iT邦幫忙

2023 iThome 鐵人賽

DAY 4
0
Modern Web

廚藝不精也可以,給自己做一份Javascript小火鍋系列 第 4

〈Day4〉看起來像是遍歷物件的Object method

  • 分享至 

  • xImage
  •  

Table of Contents

  • Object.keys、Object.getOwnPropertyNames()
  • Object.values
  • Object.entries
  • References

遍歷的英文為Traversal,是在逐一走訪某種結構的節點、元素或屬性……使用方式跟深度都會因為結構而有所不同。
那object的這些method是一種遍歷嗎?其實只是用了這些方法,並在可列舉的物件上取得相對應的內容而已,這些會在本篇文章中再做進一步的使用說明。

Object.keys()、Object.getOwnPropertyNames()

還記得第二天提到:物件的內容由keyvalue組成。Object.keys方法的名稱即表達了其功能:它用於取得物件的所有鍵,回傳值則使用一組Array呈現。

const contestant = {
  contestantId: 1,
  contestantName: "Alice",
  hotpotFlavor: "Spicy Sichuan",
  hotpotIngredients: ["Beef slices", "Tofu", "Enoki mushrooms", "Napa cabbage"],
  summarizeCooking: function () {
    return "Balancing spicy Sichuan flavor with tender beef, tofu, and crunchy cabbage. Pairing with fragrant jasmine tea enhances the experience.";
  },
}

console.log(Object.keys(contestant));//['contestantId',  'contestantName',  'hotpotFlavor',  'hotpotIngredients',  'summarizeCooking']

Object.keys()明顯是用在物件,但用在其他型別會怎樣呢?

const contestant1 = '123';
const contestant2 = ['1','2','3'];
const contestant3 = 123;

console.log(Object.keys(contestant1));//[ '0', '1', '2' ]

//使用array,回傳一個index值陣列
console.log(Object.keys(contestant2));//[ '0', '1', '2' ]

//數字沒有Enumerable
console.log(Object.keys(contestant3));//[]

有沒有發現居然以正常使用,只是想不到回傳的屬性名稱用途。但是之所以會有這種現象,是因為在使用Object.keys,會讓非物件的型別強制轉形成Object,而原始型別除了string,其他型別在使用Object.keys()之後,只會回傳一個空陣列。更多可以參考coerced to objects

Object.getOwnPropertyNames()?也有類似的結果,來示範一下用法:

const contestant = {
  contestantId: 1,
  contestantName: "Alice",
  hotpotFlavor: "Spicy Sichuan",
  hotpotIngredients: ["Beef slices", "Tofu", "Enoki mushrooms", "Napa cabbage"],
  summarizeCooking: function () {
    return "Balancing spicy Sichuan flavor with tender beef, tofu, and crunchy cabbage. Pairing with fragrant jasmine tea enhances the experience.";
  },
}

console.log(Object.getOwnPropertyNames(contestant));//['contestantId',  'contestantName',  'hotpotFlavor',  'hotpotIngredients',  'summarizeCooking']

要注意的是,Object.getOwnPropertyNames()可以用在不可列舉的物件。

Object.values()

同理上述的Object.keysObject.values可以取得Object的所有值,使用該方法一樣會回傳一個Array

const contestant = {
  contestantId: 1,
  contestantName: "Alice",
  hotpotFlavor: "Spicy Sichuan",
  hotpotIngredients: ["Beef slices", "Tofu", "Enoki mushrooms", "Napa cabbage"],
  summarizeCooking: function () {
    return "Balancing spicy Sichuan flavor with tender beef, tofu, and crunchy cabbage. Pairing with fragrant jasmine tea enhances the experience.";
  },
}

console.log(Object.values(contestant));//[  1,  'Alice',  'Spicy Sichuan',  [ 'Beef slices', 'Tofu', 'Enoki mushrooms', 'Napa cabbage' ],  [Function: summarizeCooking]]

Object.entries()

如果希望一個method就可以拿到keyvalue,使用Object.entries()就能幫上忙。

const contestant = {
  contestantId: 1,
  contestantName: "Alice",
  hotpotFlavor: "Spicy Sichuan",
  hotpotIngredients: ["Beef slices", "Tofu", "Enoki mushrooms", "Napa cabbage"],
  summarizeCooking: function () {
    return "Balancing spicy Sichuan flavor with tender beef, tofu, and crunchy cabbage. Pairing with fragrant jasmine tea enhances the experience.";
  },
}

console.log(Object.entries(contestant));//印出下面每一組value/key
// [
//   [ 'contestantId', 1 ],
//   [ 'contestantName', 'Alice' ],
//   [ 'hotpotFlavor', 'Spicy Sichuan' ],
//   [
//     'hotpotIngredients',
//     [ 'Beef slices', 'Tofu', 'Enoki mushrooms', 'Napa cabbage' ]
//   ],
//   [ 'summarizeCooking', [Function: summarizeCooking] ]
// ]

//也可以再用其他array method分開來
Object.entries(contestant).forEach(item=>{
  const key = item[0];
  const value = item[1];
  console.log(key);
  console.log(value);
})

// key
// contestantId
// 1
// contestantName
// Alice
// hotpotFlavor

// value
// Spicy Sichuan
// hotpotIngredients
// [ 'Beef slices', 'Tofu', 'Enoki mushrooms', 'Napa cabbage' ]
// summarizeCooking
// [Function: summarizeCooking]

那什麽才是遍歷,明天再來講講for...in

References

  • MDN
  1. Object.keys()
  2. Object coercion
  3. Object.values()
  4. Object.entries()
  5. Object.getOwnPropertyNames()

上一篇
〈Day3〉物件基礎(下)
下一篇
〈Day5〉遍歷物件的for-in
系列文
廚藝不精也可以,給自己做一份Javascript小火鍋30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言